package com.insigma.yanwenlong.bookkeeping.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import com.insigma.yanwenlong.bookkeeping.db.jdbc.DBConnection;

public class CommonDao {
	private boolean isSuccess = false;
	//通过账户的Id删除该账户和对应的账务信息
	public boolean deleteById(int id) {
		Connection connection = DBConnection.getConnection();
		Statement statement = null;
		try {
			//设置自动提交为否，如果没有代码去提交的话，数据库里面不会生效
			connection.setAutoCommit(false);
			statement = connection.createStatement();
			
			String sql = "delete from detail where accountId = " + id;
			statement.execute(sql);
			
			sql = "delete from account where id = " + id;
			statement.execute(sql);
			
			connection.commit();
			isSuccess = true;
			
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				//有异常就回滚事务
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		
		DBConnection.closeStatement(statement);
		DBConnection.closeConnection(connection);
		
		return isSuccess;
	}
	
	//通过memberId删除该成员和对应的账务信息和对应的账户信息
	public boolean deleteBymemberId(int memberId) {
		Connection connection = DBConnection.getConnection();
		Statement statement = null;
		try {
			connection.setAutoCommit(false);
			statement = connection.createStatement();
			
			String sql = "delete from detail where memberId = " + memberId;
			statement.execute(sql);
			
			sql = "delete from account where memberId = " + memberId;
			statement.execute(sql);
			
			
			
			sql = "delete from member where id = " + memberId;
			statement.execute(sql);
			
			connection.commit();
			isSuccess = true;
			
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		
		DBConnection.closeStatement(statement);
		DBConnection.closeConnection(connection);
		
		return isSuccess;
	}
	
	//通过categoryId删除该类别和对应的账务信息
	public boolean deleteCategoryById(int categoryId) {
		Connection connection = DBConnection.getConnection();
		Statement statement = null;
		try {
			connection.setAutoCommit(false);
			statement = connection.createStatement();
			
			String sql = "delete from detail where categoryId = " + categoryId;
			statement.execute(sql);
			
			sql = "delete from category where id = " + categoryId;
			statement.execute(sql);
			
			connection.commit();
			isSuccess = true;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		
		DBConnection.closeStatement(statement);
		DBConnection.closeConnection(connection);
		
		return isSuccess;
	}
}
